package com.openbravo.pos.forms;

import cn.ekuma.epos.POSContent;
import cn.ekuma.epos.datalogic.I_DataLogicCustomers;
import cn.ekuma.epos.module.CoreModel;
import cn.ekuma.epos.module.DefaultDataLogicModel;
import com.openbravo.data.basic.BasicException;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.loader.DBSession;
import com.openbravo.data.loader.TableDBSentenceBuilder;
import com.openbravo.data.loader.sentence.batch.BatchSentence;
import com.openbravo.data.loader.sentence.batch.BatchSentenceResource;
import com.openbravo.pos.base.*;
import com.openbravo.pos.model.BaseSwingModel;
import e.odbo.data.dao.EntityManager;
import e.odbo.data.security.NoScuritySupportManager;

import javax.swing.*;
import java.awt.*;
import java.util.List;
import java.util.regex.Matcher;

public class PosSwingApp extends AbstractPosSwingApp {
	
	private I_DataLogicCustomers m_dlCustomer;
	AppView appView;
	private boolean isRemoteModel;
	private BaseSwingModel swingModel;
	
	
	public PosSwingApp(AppProperties props,AppView app) {
		super(props);
		this.appView=app;
	}

	@Override
	public boolean initApp(AppProperties props) {

		try {
			modelManager.addModel(new CoreModel(appView));	
		} catch (BasicException e3) {
			// TODO Auto-generated catch block
			e3.printStackTrace();
			return false;
		}  
		
		String linkModel=props.getProperty(AppConfig.LINK_MODE);
        if(linkModel==null)
        	linkModel="false";
        
        
		if("true".equalsIgnoreCase(linkModel)){
            //session=new SessionWrap();
            //isRemoteModel=true;
        }else{
        	 // Database start
            try {
                session = new AppViewConnection().createSession(props);
            } catch (BasicException e) {
                JMessageDialog.showMessage((Component) appView.getAppUserView(), new MessageInf(MessageInf.SGN_DANGER, e.getMessage(), e));
                return false;
            }
        }
 
		//modelManager.setSession(session);
        EntityManager entityManager=new EntityManager(session,new TableDBSentenceBuilder((DBSession) session,new NoScuritySupportManager()));
        DefaultDataLogicModel dataLogicModel=new DefaultDataLogicModel(entityManager);
   try{
       modelManager.addModel(dataLogicModel);
        swingModel=new BaseSwingModel();
        modelManager.addModel(swingModel);
    } catch (BasicException e3) {
		e3.printStackTrace();
		return false;
	}  
    
        m_dlSystem = swingModel.getDLSystem();
        m_dlCustomer=swingModel.getDLCustomer();
        
        if(!isRemoteModel&&!initLocalModel())
    		return false;
		
		return true;
	}

	
	 public boolean initLocalModel(){ 
        // Create or upgrade the database if database version is not the expected
        String sDBVersion = readDataBaseVersion(POSContent.APP_ID);
        System.out.println(" 版本比较 db:"+sDBVersion+"  and app:"+POSContent.APP_VERSION);
        if (!POSContent.APP_VERSION.equals(sDBVersion)) {
            // Create or upgrade database
          String sScript = sDBVersion == null
                    ? m_dlSystem.getInitScript() + "-create.sql"
                    : m_dlSystem.getInitScript() + "-upgrade-" + sDBVersion + ".sql";
            if (JRootApp.class.getResource(sScript) == null) {
                JMessageDialog.showMessage((Component) appView.getAppUserView(), new MessageInf(MessageInf.SGN_DANGER, sDBVersion == null
                            ? AppLocal.getIntString("message.databasenotsupported", session.getDialect().getName()) // Create script does not exists. Database not supported
                            : AppLocal.getIntString("message.noupdatescript"))); // Upgrade script does not exist.
                session.close();
                return false;
            } else {
                // Create or upgrade script exists.
                if (JOptionPane.showConfirmDialog((Component) appView.getAppUserView()
                        , AppLocal.getIntString(sDBVersion == null ? "message.createdatabase" : "message.updatedatabase")+"<--"+sScript
                        , AppLocal.getIntString("message.title")
                        , JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {

                    try {                         
                        java.util.List l = exeSQLScript(sScript);
                        if (l.size() > 0) {
                            JMessageDialog.showMessage((Component) appView.getAppUserView(), new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("Database.ScriptWarning"), l.toArray(new Throwable[l.size()])));
                        }
                   } catch (BasicException e) {
                        JMessageDialog.showMessage((Component) appView.getAppUserView(), new MessageInf(MessageInf.SGN_DANGER, AppLocal.getIntString("Database.ScriptError"), e));
                        session.close();
                        return false;
                    }
                } else {
                    session.close();
                    return false;
                }
                
                if (JOptionPane.showConfirmDialog((Component) appView.getAppUserView()
                        , AppLocal.getIntString( "message.importSampleDate" )+"<--"+sScript
                        , AppLocal.getIntString("message.title")
                        , JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
                	return insertSampleDate();
                }
            }
        }
        return true;
    }
	
	 
	 
	protected boolean insertSampleDate(){
		 String sScript = m_dlSystem.getInitScript() + "-sample.sql";
         if (JRootApp.class.getResource(sScript) == null) {
             JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_DANGER, AppLocal.getIntString("message.noupdatescript"))); // Upgrade script does not exist.
             session.close();
             return false;
         } else {
                 try { 
                     java.util.List l = exeSQLScript(sScript);
                     if (l.size() > 0) {
                         JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("Database.ScriptWarning"), l.toArray(new Throwable[l.size()])));
                     }
                } catch (BasicException e) {
                     JMessageDialog.showMessage(new java.awt.Frame(), new MessageInf(MessageInf.SGN_DANGER, AppLocal.getIntString("Database.ScriptError"), e));
                     session.close();
                     return false;
             }
         }
     return true;
	}
	
	

	public I_DataLogicCustomers getM_dlCustomer() {
		return m_dlCustomer;
	}

	public BaseSwingModel getSwingModel() {
		return swingModel;
	}


    protected List exeSQLScript(String sScript) throws BasicException{
        BatchSentence bsentence = new BatchSentenceResource(session, sScript);
        bsentence.putParameter("APP_ID", Matcher.quoteReplacement(POSContent.APP_ID));
        bsentence.putParameter("APP_NAME", Matcher.quoteReplacement(POSContent.APP_NAME));
        bsentence.putParameter("APP_VERSION", Matcher.quoteReplacement(POSContent.APP_VERSION));
        //bsentence.putParameter("AD_CLIENT_ID", Matcher.quoteReplacement(AppConfig.getAppProperty(Adempiere.AD_CLIENT_ID)));
        //bsentence.putParameter("AD_ORG_ID", Matcher.quoteReplacement(AppConfig.getAppProperty(Adempiere.AD_ORG_ID)));

        return bsentence.list();
    }
	
}
